<template>
  <el-button v-bind="{loading:loading,...$attrs}"
             v-on="listeners"
             class="z-button">
    <slot>
      {{name}}
    </slot>
  </el-button>
</template>

<script>
import { debounce } from 'lodash'
export default {
  name: 'ZButton',
  props: {
    name: {
      type: String
    },
    buffer: {
      type: Number,
      default: 2
    },
    throttle: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      loading: false
    }
  },
  computed: {
    listeners () {
      return {
        ...this.$listeners,
        click: this.throttleClick
      }
    }
  },
  methods: {
    throttleClick (event) {
      if (!this.throttle) {
        return this.$emit('click', event)
      }
      this.loading = true

      let count = 0

      const done = debounce(() => {
        if (count < this.buffer) {
          return done()
        }
        this.loading = false
      }, 1000)

      this.$emit('click', event, done)

      const timer = window.setInterval(() => {
        count++
        if (count >= this.buffer) {
          window.clearInterval(timer)
        }
      }, 1000)
    }
  }
}
</script>
